﻿#region License
// Copyright 2009 Buu Nguyen (http://www.buunguyen.net/blog)
// 
// Licensed under the Apache License, Version 2.0 (the "License"); 
// you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at 
// 
// http://www.apache.org/licenses/LICENSE-2.0 
// 
// Unless required by applicable law or agreed to in writing, software 
// distributed under the License is distributed on an "AS IS" BASIS, 
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
// See the License for the specific language governing permissions and 
// limitations under the License.
// 
// The latest version of this file can be found at http://dotcommon.codeplex.com
#endregion

using System;
using System.Web;
using System.Web.Mvc;

namespace DotCommon.Mvc
{
    /// <summary>
    /// Filter to sends appropriate cache & expire response headers so that the 
    /// browser can cache the response of this controller/action.
    /// </summary>
    public class CacheFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Duration in seconds to cache the response.
        /// Default is 60 seconds.
        /// </summary>
        public int Duration { get; set; }

        public CacheFilterAttribute()
        {
            Duration = 60;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (Duration <= 0) 
                return;
            var cache = filterContext.HttpContext.Response.Cache;
            cache.VaryByHeaders["Accept-Encoding"] = true;
            cache.SetOmitVaryStar(true);
            cache.SetMaxAge(TimeSpan.FromSeconds(Duration));
            cache.SetLastModified(DateTime.Now);
            cache.SetValidUntilExpires(true);
            cache.SetCacheability(HttpCacheability.Public);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

            // For HTTP 1.0 browsers 
            cache.SetExpires(DateTime.Now.Add(TimeSpan.FromSeconds(Duration))); 
        }
    }
}
